package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.properties.JwtProperties;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.EmployeeService;
import org.apache.http.impl.io.EmptyInputStream;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        // 获取前端发送的用户名和密码
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /*
    1.新增员工
     */
    @Override
    public void save(EmployeeDTO employeeDTO) {
        // 拷贝对象属性
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO,employee);

        // 设置账号的状态，默认为正常
        employee.setStatus(StatusConstant.ENABLE);
        // 设置密码，默认为123456
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));

//        // 设置当前记录的创建时间和修改时间
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
//        // 设置当前记录创建人id和修改人id
//        employee.setCreateUser(BaseContext.getCurrentId());
//        employee.setUpdateUser(BaseContext.getCurrentId());

        employeeMapper.inset(employee);
    }

    /*
    2.根据名字分页查询员工
     */
    @Override
    public PageResult pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {
        // 利用pageHelper分页查询
        PageHelper.startPage(employeePageQueryDTO.getPage(),employeePageQueryDTO.getPageSize());
        // 调用empmapper进行姓名查询
        List<Employee> allEmp = employeeMapper.query(employeePageQueryDTO);
        // 通过PageHelper中的Page将所有员工集合进行强转，将符合条件的员工进行分页
        Page<Employee> p = (Page<Employee>) allEmp;
        // 结果返回到PageResult中
        long total = p.getTotal(); // 获取总数
        List<Employee> result = p.getResult();// 获取数据
        return new PageResult(total,result);
    }

    // 3.启动禁用员工
    @Override
    public void startOrStop(Integer status, Long id) {
        Employee employee = Employee.builder()
                .status(status)
                .id(id)
                .build();
        employeeMapper.update(employee);
    }
    // 4.编辑员工信息（两个接口）
    // 4.1 根据id查询员工（对应编辑按钮）
    @Override
    public Employee getByID(Long id) {
        Employee employee = employeeMapper.getByID(id);
        employee.setPassword("****");
        return employee;
    }
    // 4.2 根据传入json数据保存员工数据（对应保存按钮）
    @Override
    public void update(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO,employee);
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.update(employee);
    }
    // 5.修改员工密码

    @Override
    public void editPassword(PasswordEditDTO passwordEditDTO) {
        // 获取当前登录的userId
        Long currentId = BaseContext.getCurrentId();
        // 通过当前登录的userId获取对应的员工
        Employee employee = employeeMapper.getByID(currentId);
        // 比较传入的密码（旧密码）和当前登录员工的密码，如果不一样，则修改失败
        // 先将传入的旧密码进行加密
        String oldPassword = passwordEditDTO.getOldPassword();
        oldPassword = DigestUtils.md5DigestAsHex(oldPassword.getBytes());
        if(!oldPassword.equals(employee.getPassword())){
            throw new PasswordErrorException(MessageConstant.PASSWORD_EDIT_FAILED);
        }
        // 如果一样，则修改密码为传入密码
        // 获得passwordEditDTO里面的新密码
        String newPassword = passwordEditDTO.getNewPassword();
        // 将新密码加密
        newPassword = DigestUtils.md5DigestAsHex(newPassword.getBytes());
        // 将当前员工的密码设为加密后的新密码
        employee.setPassword(newPassword);
        employeeMapper.update(employee);
    }
}